package eo.entityManager.locator.impl;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import eo.entityManager.locator.EntityManagerLocator;

public class ThreadLocalEntityManagerLocator implements EntityManagerLocator {

    private final EntityManagerFactory factory;

    private final ThreadLocal<EntityManager> entities = new ThreadLocal<EntityManager>();

    public ThreadLocalEntityManagerLocator(EntityManagerFactory factory) {
        super();
        this.factory = factory;
    }

    public EntityManager findEntityManager() {
        EntityManager em = entities.get();
        if (em != null) {
            if (em.isOpen()) {
                return em;
            }
            entities.remove();
        }
        em = this.factory.createEntityManager();
        entities.set(em);
        return em;
    }

    public EntityManagerFactory getEntityManagerFactory() {
        return factory;
    }

    public void closeEntityManager() {
        EntityManager em = entities.get();
        if (em != null && em.isOpen()) {
            em.close();
        }
        entities.remove();
    }

}
